package com.example.foo.api.boot;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.example.core.AppException;

@org.springframework.web.bind.annotation.RestControllerAdvice
public class UncaughtExceptionHandler extends org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler {

	private final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(getClass());

	@ExceptionHandler(value = { Exception.class })
	public ResponseEntity<Object> handleUncaughtException(Exception ex) {
		logger.error("Uncaught exception", ex);
		Map<String, Object> data = new HashMap<>(2);
		data.put("code", resolveCode(ex));
		data.put("msg", resolveMsg(ex));
		return new ResponseEntity<>(data, null, HttpStatus.INTERNAL_SERVER_ERROR);
	}

	@ExceptionHandler(value = { UnauthorizedException.class })
	public ResponseEntity<Object> handleUncaughtUnauthorizedException(UnauthorizedException ex) {
		logger.warn("Unauthorized exception: {}", ex.getMessage());
		return new ResponseEntity<>(null, null, HttpStatus.UNAUTHORIZED);
	}

	private static String resolveCode(Exception ex) {
		if (ex instanceof AppException) {
			return ex.getClass().getSimpleName();
		}
		return "InternalServerError";
	}

	private static String resolveMsg(Exception ex) {
		if (ex instanceof AppException) {
			return ex.getMessage();
		}
		return "系统错误";
	}

}
